package com.zjl.search.service;

import com.alibaba.fastjson.JSON;
import com.zjk.pojo.product.SearchItem;
import com.zjl.search.feign.ProductFeignClient;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: gfk
 * @create: 2022/11/4
 * @Description:
 * @FileName: ESSybcService
 * @History:
 * @自定义内容：
 */
@Service
public class ESSybcService {
    @Autowired
    ProductFeignClient productFeignClient;

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Autowired
    RedisTemplate redisTemplate;

    @Value("${exam5.elasticsearch.index}")
    private String index;

    @Scheduled(cron = "0/10 * * * * *")
    private void sync_Es(){

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("进入定时器"+simpleDateFormat.format(new Date()));

        Map searchMap = new HashMap<>();
        String lastSyncTime = (String) redisTemplate.opsForValue().get("lastSyncTime");
        if (!StringUtils.isEmpty(lastSyncTime)){
            searchMap.put("lastSyncTime",lastSyncTime);
        }
        List<SearchItem> searchItemList = productFeignClient.findSearchItem(searchMap);

        searchItemList.stream().forEach((searchItem)->{
            IndexRequest indexRequest = new IndexRequest(index);
            indexRequest.id(searchItem.getId().toString());
            String jsonString = JSON.toJSONString(searchItem);
            indexRequest.source(jsonString,XContentType.JSON);
            try {
                restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        int size = searchItemList.size();

        System.out.println("一共"+size+"条");
        //最后更新同步时间
        redisTemplate.opsForValue().set("lastSyncTime", simpleDateFormat.format(new Date()));
    }
}
